package cn.zk.solution.client;

import cn.zk.solution.coder.MyMessageDecoder;
import cn.zk.solution.coder.MyMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

public class TcpClient {
    // 主机地址
    private final String host;
    // 端口
    private final int port;

    public TcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    // 客户端配置
    public void run() throws InterruptedException {
        // group
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // bootstrap + 客户端配置
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 加入编码器
                            pipeline.addLast(new MyMessageEncoder());
                            // 添加解码器
                            pipeline.addLast(new MyMessageDecoder());
                            // 自定义handler
                            pipeline.addLast(new TcpClientHandler());
                        }
                    });
            // 连接服务器
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 从控制台数据消息并发送
            Channel channel = channelFuture.channel();
            System.out.println("==>["+channel.localAddress()+"]连接服务器成功！");
            // 监听关闭事件
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 关闭
            group.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws InterruptedException {
        TcpClient client = new TcpClient("127.0.0.1", 8081);
        client.run();
    }
}
